import { ProFormInstance } from "@ant-design/pro-components";
import {  useRef, useState } from "react";
import {  createCodeApi, selectByParentIdApi, selectOneApi, updateApi } from "./services";
import {  message } from "antd";
export interface colDataProps {
    /**编号*/
    id?: number;
    /**字段代码*/
    code?: string | number;
    /**字段名称*/
    name?: string | number;
    /**数据类型*/
    dataType?: string | number;
    /**数据长度*/
    dataTypeLength?: string | number;
    /**主键*/
    isKey?: string | number;
    /**可为空*/
    isNull?: string | number;
    /**插入*/
    isInsert?: string | number;
    /**编辑*/
    isEdit?: string | number;
    /**列表*/
    isList?: string | number;
    /**查询*/
    isQuery?: string | number;
    /**查询方式*/
    queryType?: string | number;
    /**必填*/
    isRequired?: string | number;
    /**显示类型*/
    htmlType?: string | number;
    /**父id */
    parentId?: number;
    /**默认值 */
    defaultValue?: string | number
}

export interface IndexInfoProps {
    id?: number,
    filedName?: any,
    comment?: string,
    indexType?: string

}
const getPublicField = () => {

    return [
        {
            id: Date.now() + 1,
            code: "id",
            name: "ID",
            dataType: "int",
            isKey: 1,
            isEdit: 1,
            isList: 1,
            isQuery: 1,
            queryType: "=",
        },
        {
            id: Date.now() + 2,
            code: "name",
            name: "名称",
            dataType: "varchar",
            dataTypeLength: 255,
            isInsert: 1,
            isEdit: 1,
            isList: 1,
            isQuery: 1,
            queryType: "LIKE",
        },
        {
            id: Date.now() + 3,
            code: "status",
            name: "状态",
            dataType: "tinyint",
            isEdit: 1,
            isList: 1,
            isQuery: 1,
            queryType: "=",
            defaultValue: 1
        },
        {
            id: Date.now() + 4,
            code: "created_at",
            name: "创建时间",
            dataType: "datetime",
            isList: 1,
            isQuery: 1,
            queryType: "BETWEEN",
        },
        {
            id: Date.now() + 5,
            code: "updated_at",
            name: "更新时间",
            dataType: "datetime",
            isList: 1,
        },
        {
            id: Date.now() + 6,
            code: "comment",
            name: "备注",
            dataType: "varchar",
            dataTypeLength: 255,
            isNull: 1,
            isInsert: 1,
            isEdit: 1,
            isList: 1,
            isQuery: 1,
            queryType: "LIKE",
        },


    ]


}




export default () => {
    const formRef = useRef<ProFormInstance<any>>();
    const [currentItem, setCurrentItem] = useState<any>({})
    const [tab, setTab] = useState('tab1');
    const [fieldInfoList, setFieldInfoList] = useState<colDataProps[]>([]);
    const [indexInfoList, setIndexInfoList] = useState<IndexInfoProps[]>([])
    const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);

    const [indexInfoKeys, setIndexInfoKeys] = useState<React.Key[]>([])

    const selectOne = async (id: any) => {
        const hide = message.loading("正在获取详情")
        const res = await selectOneApi({
            id,
            queryChildren: true,
        });
        if (res.code == 200) {
            res.data.status = !!res.data.status
            setCurrentItem(res.data);
            if (res.data.fieldInfoList.length) {
                setFieldInfoList(res.data.fieldInfoList)

            } else {
                setFieldInfoList(getPublicField())
            }
            res.data.indexInfoList.forEach((item:any)=>{
                item.filedName=item.filedName.split(",")
            })
            console.log(res.data.indexInfoList);
            
            setIndexInfoList(res.data.indexInfoList)

            formRef.current?.setFieldsValue(res.data);
        }
        hide()
    }
    const selectByParentId = async (id: number) => {
        const hide = message.loading("正在获取详情")
        const res = await selectByParentIdApi(id);
        if (res.code == 200) {
            if (res.data.length > 0) {
                setFieldInfoList([...res.data])
            } else {
                setFieldInfoList(getPublicField())

            }
        }
        hide()
    }

    const onFinish = async () => {
        const indexList = indexInfoList.map(item => ({
            ...item,
            filedName: item.filedName?.join(",")
        }))

        const submitData = {
            ...currentItem,
            indexInfoList: indexList,
            fieldInfoList: fieldInfoList
        }
        console.log("submitdata", submitData)


        const hide = message.loading("正在更新")
        const res = await updateApi(submitData)

        if (res.code == 200) {
            message.success("更新成功")
            selectOne(currentItem.id)
        }
        hide()
    }
    const addRow = () => {
        let now = Date.now()
        const list = [...fieldInfoList, { id: now }];
        setEditableRowKeys([now])
        setFieldInfoList(list)

    }
    const deleteItem = (index: number) => {
        const list = [...fieldInfoList];
        list.splice(index, 1)
        setFieldInfoList(list)


    }
    const canEditFieldInfo = (id: number) => {
        let index = editableKeys.indexOf(id);
        if (index == -1) {
            setEditableRowKeys([...editableKeys, id])

        } else {
            let l = [...editableKeys];
            l.splice(index, 1)
            setEditableRowKeys(l)
        }

    }


    const addIndexInfoRow = () => {
        let now = Date.now()
        const list = [...indexInfoList, { id: now }];
        setIndexInfoKeys([now])
        setIndexInfoList(list)

    }
    const deleteIndexInfoItem = (index: number) => {
        const list = [...indexInfoList];
        list.splice(index, 1)
        setIndexInfoList(list)


    }

        const canEditIndexInfo = (id: number) => {
        let index = indexInfoKeys.indexOf(id);
        if (index == -1) {
            setIndexInfoKeys([...indexInfoKeys, id])

        } else {
            let l = [...indexInfoKeys];
            l.splice(index, 1)
            setIndexInfoKeys(l)
        }

    }
    const createCodeClick = async ()=>{
        const hide = message.loading('正在提交---')
        const id = currentItem.id;
        const res = await createCodeApi({id});
        if(res.code==200){
            message.success("生成成功")
        }
        hide()


    }

    return {
        formRef,
        tab,
        setTab,
        currentItem,
        setCurrentItem,
        selectOne,
        selectByParentId,

        fieldInfoList,
        setFieldInfoList,
        editableKeys,
        setEditableRowKeys,
        onFinish,
        addRow,
        deleteItem,
        indexInfoList,
        setIndexInfoList,
        addIndexInfoRow,
        deleteIndexInfoItem,
        indexInfoKeys,
        setIndexInfoKeys,
        canEditFieldInfo,
        canEditIndexInfo,
        createCodeClick,


    };
};